package replicator

import (
	"dts/log"
	"dts/sqltypes"
	"fmt"
	"strings"
)

var CopyHistoryLog = copyHistory{}

type copyHistory struct{}

const InsertLimit = 10

func rowToTotal(row []sqltypes.Value) (int64, error) {
	total, err := row[0].ToInt64()
	if err != nil {
		return 0, err
	}

	return total, err
}

func (c *copyHistory) GetCnt(db *DBClient, replId int, dbName string, tableName string) (int64, error) {
	sql := fmt.Sprintf("select count(id) from replicator.copy_history where repl_id = %d and dbname='%s' and table_name='%s'", replId, dbName, tableName)

	res, err := db.Execute(sql)
	if err != nil {
		log.Error(err.Error())
		return 0, err
	}

	total, err := rowToTotal(res.Rows[0])

	if err != nil {
		log.Error(err.Error())
		return 0, err
	}

	return total, nil
}

func (c *copyHistory) Insert(db *DBClient, replId int, dbName string, tableName string) (uint64, error) {

	total, err := c.GetCnt(db, replId, dbName, tableName)

	if err != nil {
		return 0, err
	}

	if total >= InsertLimit {
		log.Error("taskId:%d db:%s table:%s has reached max value %d", replId, dbName, tableName, total)
		return 0, nil
	}

	var buf strings.Builder
	buf.WriteString("insert into replicator.copy_history(repl_id, dbname, table_name) values ")

	fmt.Fprintf(&buf, "(%d, %s, %s)", replId, encodeString(dbName), encodeString(tableName))

	fmt.Println(buf.String())
	res, err := db.Execute(buf.String())
	if err != nil {
		log.Error(err.Error())
		return 0, err
	}

	return res.InsertID, nil
}

func (c *copyHistory) Update(db *DBClient, id uint64, cnt int) error {
	if id < 1 {
		return nil
	}
	sql := fmt.Sprintf("update replicator.copy_history set cnt= cnt + %d,used_time=UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(created_at) where id = %d", cnt, id)
	_, err := db.Execute(sql)
	if err != nil {
		log.Error(err.Error())
		return err
	}

	return nil
}
